package com.yc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.dao.ResfoodMapper;
import com.yc.domain.MyPageBean;
import com.yc.domain.Resfood;
import com.yc.service.ResfoodBiz;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Slf4j
@Transactional
public class ResfoodImpl implements ResfoodBiz {


    @Autowired
    ResfoodMapper resfoodDao;

    @Value("${spring.cache.cacheName}")
    String cacheName;
	@Cacheable(cacheNames = "#{cacheName}",key = "'all'")
	@Override
	public List<Resfood> findAll() {
        LambdaQueryWrapper<Resfood> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.orderByDesc(Resfood::getFid);
        return resfoodDao.selectList(lambdaQuery);
	}

	@Override
	@Cacheable(cacheNames = "#{cacheName}",key = "#fid")
	public Resfood findById(Integer fid) {
		LambdaQueryWrapper<Resfood> lambdaQuery = Wrappers.lambdaQuery();
		//按照id查找
		lambdaQuery.eq(Resfood::getFid, fid);
		return resfoodDao.selectOne(lambdaQuery);
	}

	@Override
	public List<Resfood> findFoods(Resfood food, int pageno, int pagesize, String sortby, String sort) {

		return null;
	}

	@Override
	public MyPageBean findByPage(MyPageBean page) {
		// 创建分页对象
		IPage<Resfood> ipage = new Page<>(page.getPageno(), page.getPagesize());

		// 创建查询包装器
		QueryWrapper<Resfood> queryWrapper = new QueryWrapper<>();

		// 确定排序方式
		if ("asc".equalsIgnoreCase(page.getSort())) {
			queryWrapper.orderByAsc(page.getSortby());
		} else {
			queryWrapper.orderByDesc(page.getSortby());
		}

		// 执行分页查询
		 resfoodDao.selectPage(ipage, queryWrapper);
		//数据
		page.setList(ipage.getRecords());
		//数据总条数
		page.setTotal(ipage.getTotal());
		//总页数
		page.setTotalpage(ipage.getPages());
		return page;
	}

    @Override
    public int addResfood(Resfood food) {

		 resfoodDao.insert(food);
		 return food.getFid();
	}
}
